package com.gyw.myapplication;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;

import com.google.gson.Gson;
import com.gyw.myapplication.compare.TableView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by yangyi on 2018/12/8.
 */

public class CompareActivity extends AppCompatActivity {


    @BindView(R.id.table_view)
    TableView tableView;
    @BindView(R.id.btn_add)
    Button btnAdd;

    @OnClick(R.id.btn_add)
    public void onClick() {
        CarData carData=new CarData();
        carData.setSpecName("添加");
        int i=carDatas.size()-1;
        carDatas.add(i,carData);
        carTableAdapter.notifyDataChanged();
    }

    class DataBean {
        List<CarData> data;
    }

    private CarTableAdapter carTableAdapter;
    private List<CarData> carDatas;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compare);
        ButterKnife.bind(this);
        String data = getJson("comparedata.json", this);
        Gson gson = new Gson();
        DataBean dataBean = gson.fromJson(data, DataBean.class);
        carDatas = dataBean.data;
        carTableAdapter = new CarTableAdapter(carDatas, this);
        tableView.setAdapter(carTableAdapter);
    }


    public static void actionStart(Context context) {
        Intent intent = new Intent(context, CompareActivity.class);
        context.startActivity(intent);
    }

    public String getJson(String fileName, Context context) {
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //获取assets资源管理器
            AssetManager assetManager = context.getAssets();
            //通过管理器打开文件并读取
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }


}
